//
//  CLReadModel+Mark.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/29.
//

#import "CLReadModel+Mark.h"
#import "CLBook.h"
@implementation CLReadModel (Mark)
/// 添加书签,默认使用当前阅读记录!
- (void)insetMark:(CLReadRecordModel * _Nullable)recordModel {
    
    recordModel = recordModel ? recordModel : self.recordModel;
    
    CLReadMarkModel *markModel = [[CLReadMarkModel alloc]init];
    
    markModel.bookid = recordModel.bookid;
    
    markModel.chapterid = recordModel.chapterModel.chapterid;
    
    if (recordModel.pageModel == nil || recordModel.pageModel.isHomePage) {
        
        markModel.name = @"(无章节名)";
        
        markModel.content = self.title;
        
    }else{
        
        markModel.name = recordModel.chapterModel.name;
        
        markModel.content = recordModel.contentString.removeSEHeadAndTail.removeEnterAll;
    }
    
    markModel.time = [[NSDate date] timeIntervalSince1970];//NSNumber(value: Timer1970())
    
    markModel.location = recordModel.locationFirst;
    
    if (self.markModels == nil || [self.markModels isEmpty]) {
        [self.markModels addObject:markModel];
    }else{
        [self.markModels insertObject:markModel atIndex:0];
    }
    
    [self save];
}

/// 移除当前书签
- (BOOL)removeMark:(NSInteger)index {
    
    [self.markModels removeObjectAtIndex:index];
    
    [self save];
    
    return YES;
}

/// 移除当前书签
- (BOOL)removeMarkWithRecordModel:(CLReadRecordModel *)recordModel {
    recordModel = recordModel ? recordModel : self.recordModel;
    
    CLReadMarkModel *markModel = [self isExistMark:recordModel];
    
    if (markModel != nil) {
        
        NSInteger index = [self.markModels indexOfObject:markModel];
        
        return [self removeMark:index];
    }
    
    return NO;
}

/// 是否存在书签
- (CLReadMarkModel *)isExistMark:(CLReadRecordModel *)recordModel {
    
    if (self.markModels == nil || self.markModels.isEmpty) { return nil; }
    
    recordModel = recordModel ? recordModel : self.recordModel;
    
    NSUInteger locationFirst = recordModel.locationFirst;
    
    NSUInteger locationLast = recordModel.locationLast;
    
    for (CLReadMarkModel *markModel in self.markModels) {
        if ([markModel.chapterid isEqualToString:recordModel.chapterModel.chapterid]) {
            if ((markModel.location >= locationFirst) && (markModel.location < locationLast)) {
                return markModel;
            }
        }
    }
    
    return nil;
}
@end
